﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using EPiServer.Core;

namespace EPiBoost.Core.Infrastructure
{
	public class HttpExceptionHandler
	{
		public string ErrorPage404Url { get; set; }
		public string ErrorPage500Url { get; set; }

		public static bool CustomErrorsEnabled
		{
			get
			{
				var config = WebConfigurationManager.OpenWebConfiguration("~");
				CustomErrorsSection section = (CustomErrorsSection) config.GetSection("system.web/customErrors");

				if (section != null)
				{
					return section.Mode == CustomErrorsMode.On || (section.Mode == CustomErrorsMode.RemoteOnly && IsRemoteUser);
				}
				return false;
			}
		}

		private static bool IsRemoteUser
		{
			get
			{
				var host = HttpContext.Current.Request.UserHostAddress;
				return !(host == "127.0.0.1" || host == "::1");
			}
		}


		public void HandleStatusCode(HttpResponse response, int statusCode = -1)
		{
			statusCode = statusCode == -1 ? response.StatusCode : statusCode;
			
			switch(statusCode)
			{
				case 404:
					SetResponse(response, ErrorPage404Url);
					break;
				case 500:
					if (CustomErrorsEnabled)
					{
						SetResponse(response, ErrorPage500Url);
					}
					break;
				default:
					break;
			}
		}

		public void SetResponse(HttpResponse response, string url)
		{
			if(url.StartsWith("/"))
			{
				var uri = new UriBuilder(HttpContext.Current.Request.Url);
				uri.Path = url;
				url = uri.ToString();
			}

			if(!string.IsNullOrEmpty(url))
			{
				var newBody = Helpers.ResponseHelper.GetResponseFromUrl(url);
				response.ClearContent();
				response.Write(newBody);	
			}
		}

		
	}
}
